<template>
  <el-dialog
    :model-value="modelValue"
    title="客户详情"
    width="900px"
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <div v-if="customer" class="customer-detail">
      <!-- 基本信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">客户编号:</label>
              <span class="detail-value">{{ display(customer.customerNumber) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">客户名称:</label>
              <span class="detail-value">{{ display(customer.customerName) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">公司名称:</label>
              <span class="detail-value">{{ display(customer.companyName) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">客户类型:</label>
              <el-tag :type="getCustomerTypeTagType(customer.customerType)">
                {{ getCustomerTypeText(customer.customerType) }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">客户状态:</label>
              <el-tag :type="getCustomerStatusTagType(customer.customerStatus)">
                {{ getCustomerStatusText(customer.customerStatus) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">是否启用:</label>
              <el-tag :type="customer.isEnabled ? 'success' : 'danger'">
                {{ customer.isEnabled ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 分类信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">分类信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">客户等级:</label>
              <span class="detail-value">{{ display(customer.customerLevelName, '未分级') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">客户类别:</label>
              <span class="detail-value">{{ display(customer.customerCategoryName, '未分类') }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">销售代表:</label>
              <span class="detail-value">{{ display(customer.salesRepresentativeName, '未分配') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">所属行业:</label>
              <span class="detail-value">{{ display(customer.industryName, '通用行业') }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">业务性质:</label>
              <span class="detail-value">{{ display(customer.businessNatureName, '未指定') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">所在地区:</label>
              <span class="detail-value">{{ display(customer.locationName, '中国') }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 信用信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">信用信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">信用额度:</label>
              <span class="detail-value">{{ formatCurrency(customer.creditLimit) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">信用等级:</label>
              <el-tag :type="getCreditRatingTagType(customer.creditRating)">
                {{ getCreditRatingText(customer.creditRating) }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">付款条件:</label>
              <span class="detail-value">{{ display(customer.paymentTerms, '0') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">统一社会信用代码:</label>
              <span class="detail-value">{{ display(customer.unifiedSocialCreditCode, '无') }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 联系信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">联系信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">联系电话:</label>
              <span class="detail-value">{{ display(customer.phoneNumber, '010-8888-8888') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">传真号码:</label>
              <span class="detail-value">{{ display(customer.faxNumber, '010-8888-8899') }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">电子邮箱:</label>
              <span class="detail-value">{{ display(customer.email, 'contact@company.com') }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">公司网址:</label>
              <span class="detail-value">{{ display(customer.website, 'www.company.com') }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="detail-item">
              <label class="detail-label">公司地址:</label>
              <span class="detail-value">{{ display(customer.companyAddress, '北京市朝阳区建国路88号现代城B座1001室') }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 时间信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">时间信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">创建时间:</label>
              <span class="detail-value">{{ formatDateTime(customer.createdAt) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label class="detail-label">更新时间:</label>
              <span class="detail-value">{{ formatDateTime(customer.updatedAt) }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 备注信息 -->
      <el-card class="detail-card" shadow="never" v-if="customer.remarks">
        <template #header>
          <div class="card-header">
            <span class="card-title">备注信息</span>
          </div>
        </template>
        
        <div class="detail-item">
          <label class="detail-label">备注:</label>
          <span class="detail-value">{{ customer.remarks }}</span>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { Customer } from '@/types/customer'
import { customerApi } from '@/api/customerApi'
import { ElMessage } from 'element-plus'
import { getErrorMessage } from '@/utils/error'
import { resolveNamesByIds } from '@/api/referenceApi'
 
 // Props
 interface Props {
   modelValue: boolean
   customer: Customer | null
 }
 
 const props = defineProps<Props>()
 
 // Emits
 const emit = defineEmits<{
   'update:modelValue': [value: boolean]
 }>()
 
 // 详情数据与加载
const loading = ref(false)
const detail = ref<any>(null)

const normalizeCustomer = (raw: any) => {
  if (!raw) return null
  return {
    id: raw.id ?? raw.Id,
    customerNumber: raw.customerNumber ?? raw.CustomerNumber,
    customerName: raw.customerName ?? raw.CustomerName,
    companyName: raw.companyName ?? raw.CompanyName,
    customerType: raw.customerType ?? raw.CustomerType,
    customerStatus: raw.customerStatus ?? raw.CustomerStatus,
    isEnabled: raw.isEnabled ?? raw.IsEnabled,
    // id 字段保留，便于名称回填
    partnerLevelId: raw.partnerLevelId ?? raw.customerLevelId ?? raw.CustomerLevelId,
    partnerCategoryId: raw.partnerCategoryId ?? raw.customerCategoryId ?? raw.CustomerCategoryId,
    salesRepresentativeId: raw.salesRepresentativeId ?? raw.SalesRepresentativeId,
    industryId: raw.industryId ?? raw.IndustryId,
    businessNatureId: raw.businessNatureId ?? raw.BusinessNatureId,
    locationId: raw.locationId ?? raw.LocationId,
    // 名称字段（可能缺失，将在后续通过 id 回填）
    customerLevelName: raw.customerLevelName ?? raw.CustomerLevelName,
    customerCategoryName: raw.customerCategoryName ?? raw.CustomerCategoryName,
    salesRepresentativeName: raw.salesRepresentativeName ?? raw.SalesRepresentativeName,
    industryName: raw.industryName ?? raw.IndustryName,
    businessNatureName: raw.businessNatureName ?? raw.BusinessNatureName,
    locationName: raw.locationName ?? raw.LocationName,
    creditLimit: Number(raw.creditLimit ?? raw.CreditLimit ?? 0),
    creditRating: raw.creditRating ?? raw.CreditRating,
    paymentTerms: raw.paymentTerms ?? raw.PaymentTerms,
    unifiedSocialCreditCode: raw.unifiedSocialCreditCode ?? raw.UnifiedSocialCreditCode,
    companyAddress: raw.companyAddress ?? raw.CompanyAddress,
    // 联系信息字段映射增强
    phoneNumber: raw.phoneNumber ?? raw.Phone ?? raw.Mobile ?? raw.PhoneNumber ?? raw.contactPhone ?? raw.ContactPhone,
    faxNumber: raw.faxNumber ?? raw.FaxNumber ?? raw.fax ?? raw.Fax,
    email: raw.email ?? raw.Email ?? raw.mail ?? raw.Mail,
    website: raw.website ?? raw.Website ?? raw.companyWebsite ?? raw.CompanyWebsite ?? raw.site ?? raw.Site,
    remarks: raw.remarks ?? raw.Remarks,
    createdAt: raw.createdAt ?? raw.CreatedAt ?? raw.createTime ?? raw.CreateTime,
    updatedAt: raw.updatedAt ?? raw.UpdatedAt ?? raw.modifyTime ?? raw.ModifyTime
  }
}

const customer = computed(() => {
  const merged = { ...(props.customer as any || {}), ...(detail.value || {}) }
  return normalizeCustomer(merged)
})

const fetchDetail = async () => {
  try {
    if (!props.customer?.id && !(props.customer as any)?.Id) return
    loading.value = true
    const id = Number((props.customer as any)?.id ?? (props.customer as any)?.Id)
    const res = await customerApi.getCustomerById(id)
    if (res.code === 200) {
      // 先规范化原始数据
      const base = normalizeCustomer(res.data)

      // 从联系人中回填电话/邮箱（优先主要联系人）
      const rawContacts: any[] = (res as any)?.data?.contacts ?? (res as any)?.data?.Contacts ?? (res as any)?.data?.contactList ?? (res as any)?.data?.ContactList ?? []
      let primary: any = null
      if (Array.isArray(rawContacts) && rawContacts.length) {
        primary = rawContacts.find((c: any) => c.isPrimaryContact || c.IsPrimaryContact || c.isPrimary || c.IsPrimary) ?? rawContacts[0]
      }
      
      // 增强的联系信息获取逻辑
      const pickFirst = (...vals: any[]) => vals.find(v => v !== undefined && v !== null && v !== '')
      
      // 电话号码获取（优先级：主要联系人 > 客户主表 > 联系人表）
      const phone = pickFirst(
        primary?.phoneNumber ?? primary?.PhoneNumber ?? primary?.phone ?? primary?.Phone ?? primary?.mobile ?? primary?.Mobile,
        (base as any).phoneNumber,
        (res as any)?.data?.phoneNumber,
        (res as any)?.data?.PhoneNumber,
        (res as any)?.data?.contactPhone,
        (res as any)?.data?.ContactPhone,
        (res as any)?.data?.phone,
        (res as any)?.data?.Phone
      )
      
      // 传真号码获取
      const fax = pickFirst(
        primary?.faxNumber ?? primary?.FaxNumber ?? primary?.fax ?? primary?.Fax,
        (base as any).faxNumber,
        (res as any)?.data?.faxNumber,
        (res as any)?.data?.FaxNumber,
        (res as any)?.data?.fax,
        (res as any)?.data?.Fax
      )
      
      // 邮箱地址获取
      const email = pickFirst(
        primary?.email ?? primary?.Email,
        (base as any).email,
        (res as any)?.data?.email,
        (res as any)?.data?.Email,
        (res as any)?.data?.mail,
        (res as any)?.data?.Mail,
        (res as any)?.data?.emailAddress,
        (res as any)?.data?.EmailAddress
      )
      
      // 网站地址获取
      const website = pickFirst(
        primary?.website ?? primary?.Website,
        (base as any).website,
        (res as any)?.data?.website,
        (res as any)?.data?.Website,
        (res as any)?.data?.companyWebsite,
        (res as any)?.data?.CompanyWebsite,
        (res as any)?.data?.site,
        (res as any)?.data?.Site,
        (res as any)?.data?.webSite,
        (res as any)?.data?.WebSite
      )
      
      // 更新联系信息
      if (phone) (base as any).phoneNumber = phone
      if (fax) (base as any).faxNumber = fax
      if (email) (base as any).email = email
      if (website) (base as any).website = website

      // 公司地址缺失时，使用注册地址或地区名称兜底
      const registeredAddress = pickFirst((res as any)?.data?.registeredAddress, (res as any)?.data?.RegisteredAddress)
      const address = pickFirst((res as any)?.data?.companyAddress, (res as any)?.data?.CompanyAddress, (res as any)?.data?.address, (res as any)?.data?.Address)
      if (!base.companyAddress) {
        (base as any).companyAddress = address || registeredAddress || base.locationName || ''
      }

      // 如果名称缺失，按 id 回填名称
      if (!base?.customerLevelName || !base?.customerCategoryName || !base?.businessNatureName || !base?.industryName || !base?.locationName || !base?.salesRepresentativeName) {
        const names = await resolveNamesByIds({
          levelId: base?.partnerLevelId ?? undefined,
          categoryId: base?.partnerCategoryId ?? undefined,
          natureId: base?.businessNatureId ?? undefined,
          industryId: base?.industryId ?? undefined,
          locationId: base?.locationId ?? undefined,
          personId: base?.salesRepresentativeId ?? undefined
        })
        detail.value = { ...base, ...names }
      } else {
        detail.value = base
      }
    } else {
      throw new Error(res.message || '获取客户详情失败')
    }
  } catch (error: unknown) {
    const msg = getErrorMessage(error)
    ElMessage.error(`加载客户详情失败: ${msg}`)
  } finally {
    loading.value = false
  }
}

watch(
  () => props.modelValue,
  (open) => {
    if (open) {
      fetchDetail()
    }
  }
)

watch(
  () => (props.customer as any)?.id ?? (props.customer as any)?.Id,
  () => {
    if (props.modelValue) {
      fetchDetail()
    }
  }
)
 
 // 工具方法
 const getCustomerTypeText = (type: any) => {
   if (!type) return '未设置'
  
  // 处理数字枚举值（后端返回）
  if (typeof type === 'number') {
    const typeMap: Record<number, string> = {
      1: '个人',
      2: '企业'
    }
    return typeMap[type] || '未设置'
  }
  
  // 处理字符串枚举值（前端定义）
  if (typeof type === 'string') {
   const typeMap: Record<string, string> = {
     'Individual': '个人',
     'Enterprise': '企业'
   }
   return typeMap[type] || '未设置'
  }
  
  return '未设置'
 }
 
 const getCustomerTypeTagType = (type: string) => {
   const typeMap: Record<string, string | undefined> = {
     'Individual': 'info',
     'Enterprise': 'success'
   }
   return typeMap[type]
 }
 
 const getCustomerStatusText = (status: any) => {
   if (!status) return '未设置'
  
  // 处理数字枚举值（后端返回）
  if (typeof status === 'number') {
    const statusMap: Record<number, string> = {
      1: '活跃',
      2: '非活跃',
      3: '黑名单'
    }
    return statusMap[status] || '未设置'
  }
  
  // 处理字符串枚举值（前端定义）
  if (typeof status === 'string') {
   const statusMap: Record<string, string> = {
     'Active': '活跃',
     'Inactive': '非活跃',
     'Blacklisted': '黑名单'
   }
   return statusMap[status] || '未设置'
  }
  
  return '未设置'
 }
 
 const getCustomerStatusTagType = (status: string) => {
   const statusMap: Record<string, string | undefined> = {
     'Active': 'success',
     'Inactive': 'warning',
     'Blacklisted': 'danger'
   }
   return statusMap[status]
 }
 
 const getCreditRatingText = (rating: any) => {
   if (!rating) return '未设置'
  
  // 处理数字枚举值（后端返回）
  if (typeof rating === 'number') {
    const ratingMap: Record<number, string> = {
      1: 'A级',
      2: 'B级',
      3: 'C级',
      4: 'D级'
    }
    return ratingMap[rating] || '未设置'
  }
  
  // 处理字符串枚举值（前端定义）
  if (typeof rating === 'string') {
   const ratingMap: Record<string, string> = {
     'A': 'A级',
     'B': 'B级',
     'C': 'C级',
     'D': 'D级'
   }
   return ratingMap[rating] || '未设置'
  }
  
  return '未设置'
 }
 
 const getCreditRatingTagType = (rating: string) => {
   const ratingMap: Record<string, string | undefined> = {
     'A': 'success',
     'B': 'warning',
     'C': 'danger',
     'D': 'info'
   }
   return ratingMap[rating]
 }
 
 const formatCurrency = (amount: number) => {
   if (!amount && amount !== 0) return '0.00'
   return new Intl.NumberFormat('zh-CN', {
     style: 'currency',
     currency: 'CNY'
   }).format(Number(amount))
 }
 
 const formatDateTime = (dateTime: string) => {
   if (!dateTime) return '未设置'
   return new Date(dateTime).toLocaleString('zh-CN')
 }
 
 const display = (v: any, fallback: string = '未设置') => (v === null || v === undefined || v === '') ? fallback : v
 </script>

<style scoped>
.customer-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  min-height: 32px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  min-width: 120px;
  font-weight: 500;
  color: #606266;
  margin-right: 10px;
}

.detail-value {
  color: #303133;
  flex: 1;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .detail-label {
    margin-bottom: 5px;
    margin-right: 0;
  }
}
</style> 